package com.jb.repair.acticity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.dao.Db;
import com.jb.repair.dao.ModifyDb;
import com.jb.repair.dao.QueryDb;
import com.jb.repair.model.FileLbModel;
import com.jb.repair.model.ResultModel;
import com.jb.repair.model.YcjlModel;
import com.jb.repair.net.HttpClient;
import com.jb.repair.util.BitmapUtil;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.util.TimeUtil;
import com.jb.repair.view.TitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class ChangeRegisterActivity extends BaseActivity {

    private TitleView titleView;
    private TextView tv_devname, tv_itemname, tv_happentime;
    private EditText et_explain;
    private Db db;
    private String uploadImagePath;
    private String uploadImageFileName;
    private ImageView imageView;
    private PopupWindow window;
    HashMap<String, String> map;
    List<String> list;

    private String intro = "";
    private String fileName = "";

    private String TAG = "ChangeRegisterActivity";
    private String equip_id;
    private String abnormal_id;
    private String result_id;
    private YcjlModel abnormal;
    private String imgPath;
    private Boolean is_change = false;
    private Boolean is_img_change = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_register);
        abnormal_id = UUID.randomUUID().toString();
        result_id = getIntent().getStringExtra("resultId");
        abnormal = QueryDb.getInstance(getApplicationContext()).getAbnormalByResultId(result_id);
        db = Db.getInstance(this);
        list = new ArrayList<String>();
        map = new HashMap<String, String>();
        initview();

    }


    private void initview() {
        tv_devname = (TextView) findViewById(R.id.tv_devname);
        tv_itemname = (TextView) findViewById(R.id.tv_itemname);
        tv_happentime = (TextView) findViewById(R.id.tv_happen_date);
        et_explain = (EditText) findViewById(R.id.et_explain);
        tv_devname.setText(getIntent().getStringExtra("devName"));
        tv_itemname.setText(getIntent().getStringExtra("itemName"));
        tv_happentime.setText(TimeUtil.getSystemTime());
        equip_id = getIntent().getStringExtra("equip_id");
        et_explain.setText(abnormal.abn_describe);
        et_explain.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                is_change = true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        titleView = (TitleView) this.findViewById(R.id.titleView);
        imageView = (ImageView) findViewById(R.id.iv_iv);

        imgPath = AppConfig.UPLOAD_PATH + abnormal.attachment + ".jpg";
        File f = new File(imgPath);
        if (!f.exists()) {
            imgPath = AppConfig.ATTACHMENT_PATh + abnormal.attachment + ".jpg";
        }
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        imageView.setImageBitmap(bitmap);

        Cursor cursor = db.getCursor("Select * from TB_SYS_CODE where LABEL_CODE='03031'");
        while (cursor.moveToNext()) {
            String key = cursor.getString(cursor.getColumnIndex("CODE_NAME"));
            String value = cursor.getString(cursor.getColumnIndex("CODE"));
            list.add(key);
            map.put(key, value);
        }
        cursor.close();


        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_item, list);
        arrayAdapter.setDropDownViewResource(android.R.layout.select_dialog_item);
//        sp.setAdapter(arrayAdapter);


        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                finish();
            }

            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                intro = et_explain.getText().toString();
                ResultModel model = new ResultModel();
                model.GUID = result_id;
                model.plan_task_detail_id = getIntent().getStringExtra("planId");
                model.is_abnormal = "T";
                model.is_defect = "F";
                model.abnormal_desc = intro;
                model.equip_id = equip_id;
                model.abnormal_id = abnormal_id;
                model.attachment = uploadImageFileName;
                model.is_must_today = getIntent().getStringExtra("isMust");
                Log.i(TAG,"model.is_must_today == "+model.is_must_today);
                if (is_change) {
                    ModifyDb.getInstance(getApplicationContext()).delectByResultId(result_id);
                    Log.i("main", "A");
                    if(!is_img_change){
                        Log.i("main", "B");
                        FileLbModel fileLbmodel = new FileLbModel();
                        fileLbmodel.guid = abnormal.attachment;
                        fileLbmodel.wjmc = abnormal.attachment + ".jpg";
                        fileLbmodel.lx = "jpg";
                        fileLbmodel.clounm = "attachment";
                        fileLbmodel.table = "TB_EQ_ABNORMAL";
                        fileLbmodel.lineId = abnormal_id;
                        fileLbmodel.TIMEPOINT = TimeUtil.getSystemTime();
                        ModifyDb.getInstance(getApplicationContext()).insertFile(fileLbmodel);
                        model.attachment = abnormal.attachment;
                    }
                    ModifyDb.getInstance(ChangeRegisterActivity.this).regist(model);
                    Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
                }else {
                    MessageUtil.showToast(getApplicationContext(), "未做修改");
                }
                finish();
            }
        });


        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View popView = LayoutInflater.from(ChangeRegisterActivity.this).inflate(R.layout.layout, null);
                window = new PopupWindow(popView, 200, LinearLayout.LayoutParams.WRAP_CONTENT, true);
                window.setFocusable(true);
                ColorDrawable dw = new ColorDrawable(0x00000000);
                window.setBackgroundDrawable(dw);
                window.showAsDropDown(v);
                uploadImageFileName = UUID.randomUUID().toString();

                popView.findViewById(R.id.tv_local).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();

                        Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intentGallery, 1);//这里不一定是1，可以是任意int型的数据
                    }
                });
                popView.findViewById(R.id.tv_camera).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();

                        /* 选择拍照 核心代码*/
                        Intent intentCamera = new Intent();
                        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        intentCamera.addCategory(Intent.CATEGORY_DEFAULT);
                        File file = new File(AppConfig.UPLOAD_PATH); //path代表拍照结束后照片要保存到的目录，如/sdcard/upload/image/
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        // String uploadImageFileName = System.currentTimeMillis() + ".jpg";
                        uploadImagePath = AppConfig.UPLOAD_PATH + uploadImageFileName + ".jpg";
                        file = new File(uploadImagePath);
                        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        startActivityForResult(intentCamera, 0);

                    }
                });

            }
        });
    }

    /* 拍照返回后在 onActivityResult()方法中进行处理 */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        is_change = true;
        is_img_change = true;
        File file1 = new File(AppConfig.UPLOAD_PATH);
        if(!file1.exists()){
            file1.mkdirs();
        }
        switch (requestCode) {
            case 0:
                String path = AppConfig.UPLOAD_PATH  + uploadImageFileName + ".jpg";
                Bitmap bm1 = BitmapFactory.decodeFile(path);
                if (bm1 != null) {
                    imageView.setImageBitmap(bm1);//imageView代表要显示图片的view
                    imageView.setBackground(null);
                    FileLbModel model = new FileLbModel();
                    model.guid = uploadImageFileName;
                    model.wjmc = uploadImageFileName + ".jpg";
                    model.lx = "jpg";
                    model.clounm = "attachment";
                    model.table = "TB_EQ_ABNORMAL";
                    model.lineId = abnormal_id;
                    model.TIMEPOINT = TimeUtil.getSystemTime();
                    ModifyDb.getInstance(getApplicationContext()).insertFile(model);
                }
                break;

            case 1:
                /* 在这里对选取的图片进行处理，如上传*/
                if (data != null) {
                    Uri uri = data.getData();//这个uri指向刚才选中的图片
                    if (uri != null) {
                        //获取该图片的具体路径
                        Cursor cursor = ChangeRegisterActivity.this.getContentResolver().query(uri, null, null, null, null);
                        if (cursor.moveToFirst()) {
                            String path1 = AppConfig.UPLOAD_PATH + uploadImageFileName + ".jpg";
                            String url = cursor.getString(1);//url会指向该图片
                            Bitmap bm = BitmapFactory.decodeFile(url);
                            if (bm != null) {
                                imageView.setImageBitmap(bm);//imageView代表要显示图片的view
                                imageView.setBackground(null);
                                if (BitmapUtil.saveBitmapFile(bm, path1)) {
                                    FileLbModel model = new FileLbModel();
                                    model.guid = uploadImageFileName;
                                    model.wjmc = uploadImageFileName + ".jpg";
                                    model.lx = "jpg";
                                    model.clounm = "attachment";
                                    model.table = "TB_EQ_ABNORMAL";
                                    model.lineId = abnormal_id;
                                    model.TIMEPOINT = TimeUtil.getSystemTime();
                                    ModifyDb.getInstance(getApplicationContext()).insertFile(model);
                                }
                            }
                        }

                    }
                    break;
                }
        }

    }

}